package com.rpc.dubboRpcError.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class NettyClient {

  /*ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 30, 2000, TimeUnit.SECONDS,
      new ArrayBlockingQueue<>(10), new DefaultThreadFactory("defaultFactory", false));*/

  static ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(10);

  private static NettyClientHandler nettyClientHandler;

  //创建代理对象

  public Object getBean(final Class<?> serviceClass) {
    try {
      return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
          new Class<?>[]{serviceClass}, ((proxy, method, args) -> {

            System.out.println("代理被调用....");
            if (nettyClientHandler == null) {
              initClient("localhost", 7000);
            }

            nettyClientHandler.setPara(args[0].toString());
            return threadPoolExecutor.submit(nettyClientHandler).get();

          }));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  private static void initClient(String host, Integer port) {

    nettyClientHandler = new NettyClientHandler();

    NioEventLoopGroup clientGroup = new NioEventLoopGroup();

    try {
      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(clientGroup)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ChannelPipeline pipeline = ch.pipeline();
              pipeline.addLast("decoder", new StringDecoder());
              pipeline.addLast("encoder", new StringEncoder());
              pipeline.addLast(nettyClientHandler);
            }
          });

      bootstrap.connect(host, port).sync();
      //
      System.out.println("客户端启动成功");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      clientGroup.shutdownGracefully();
    }

  }

}
